import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:verse_systems/utils/account_util.dart';


InterceptorsWrapper cacheInterceptor = InterceptorsWrapper(
  onRequest: (options, handler) async {
    // 请求前缓存操作
    // 拼接缓存key
    var key = "${options.baseUrl}${options.path}?${options.queryParameters}";
    var responseText = await AccountUtil.getUserCache(key: key);
    if (responseText != null) {
      // 设置响应
      try {
        return handler.resolve(responseText);
      } catch (e) {
        debugPrint("出现错误 :e$e");
      }
    }
    return handler.next(options);
  },
  onResponse: (Response response, handler) async {
    // 响应前缓存操作
    RequestOptions options = response.requestOptions;
    // 拼接缓存key
    var key = "${options.baseUrl}${options.path}?${options.queryParameters}";
    // 将响应数据保存到缓存
    await AccountUtil.saveCache(key: key, data: response.data);
    // StorageUtil.save(key, response.data);
    return handler.resolve(response);
  },
  onError: (DioError error, handler) {
    final response = error.response;
    return handler.resolve(response!);
  },
);
